
class AudioDecoder : public MediaDecoder {
	public:
		AudioDecoder(AVCodecContext *avctx, AVStream *stream, int streamIndex, PlayerState *playerState);

		virtual ~AudioDecoder();

		int getAudioFrame(AVFrame *frame);

	private:
		AVPacket *packet;
		int64_t next_pts;
		AVRational next_pts_tb;
};

AudioDecoder::AudioDecoder(AVCodecContext *avctx, AVStream *stream, int streamIndex, PlayerState *playerState) : MediaDecoder(avctx, stream, streamIndex, palyerState) {
	packet = av_packet_alloc();
}

AudioDecoder::~AudioDecoder() {
	stop();
	if(packet){
		av_packet_free(packet);
		av_freep(&packet);
		packet = NULL;
	}
	ALOGI("AudioDecoder destructor");
}

int AudioDecoder::getAudioFrame(AVFrame *frame) {
	int got_frame = 0;
	int ret = 0;

	if(!frame){
		return AVERROR(ENOMEM);
	}
	av_frame_unref(frame);

	do {
		if(packetQueue->getPacket(packet) < 0){
			return -1;
		}
		//解码方法，此方法不能与旧的api昏庸，如avcodec_decode_video2，AVCodecContext必须用avcodec_open2打开,如果是音频帧需要接受frame接收多次
		ret = avcodec_send_packet(pCodecCtx, packet);
		if(ret != 0){
			av_packet_unref(packet);
			continue;
		}

		ret = avcodec_receive_frame(pCodecCtx, frame);
		av_packet_unref(packet);
		if(ret < 0){
			got_frame = 0;
			av_frame_unref(frame);
			continue;
		}else {
			got_frame = 1;		//拿到了解码后的frmae
			//重新计算frame的pts,需要同步
			/*
			typedef struct AVRational{
			    int num; ///< Numerator 分子
			    int den; ///< Denominator 分明
			} AVRational;* 就是一个分数
			*/ 
			AVRational tb = (AVRational){1, frame->sample_rate};
			//如果packet活着frame里面没有存储时间戳，如pts、dts，则可以为他们写入AV_NOPTS_VALUE
			//av_rescale_q(a,b,c)相当于a*b/c
			if(frame->pts != AV_NOPTS_VALUE){
				frame->pts = av_rescale_q(frame->pts, av_codec_get_pkt_timebase(pCodecCtx), tb);
			}else if(next_pts != AV_NOPTS_VALUE) {
				frame->pts = av_rescale_q(next_pts, next_pts_tb, tb);
			}

			if(frame->pts != AV_NOPTS_VALUE) {
				next_pts = frame->pts + frame->nb_samples;
				next_pts_tb = tb;
			}
		}
	}while(!got_frame);

	return got_frame;
}
